package com.itheima.web; /**
 * @author Xiao
 * @date 2021/9/3
 */

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //从页面获取用户名、密码、验证码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");
        //从session中获取验证码
        HttpSession session = request.getSession();
        String codeGen = (String) session.getAttribute("codeGen");
        //校验两个验证码是否一致
        boolean result = codeGen.equalsIgnoreCase(checkCode);
        if (!result) {
            //如果验证码不一致，发送错误提示信息到页面
            //return结束掉后面的注册操作
            request.setAttribute("register_msg", "Error:验证码错误");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
            return;
        }
        //如果验证码一致，执行注册逻辑
        //封装用户名、密码
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        //查询用户名是否已存在
        boolean flag = userService.register(user);
        if (flag) {
            //用户名不存在，提示注册成功，跳转到登录页面
            request.setAttribute("register_msg", "注册成功，请登录！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        } else {
            //用户名存在，提示错误信息，跳转到注册页面
            request.setAttribute("register_msg", "Error:用户名已存在");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
